package com.yunlinker.asba.activity;


import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.qiyukf.nimlib.sdk.NimIntent;
import com.qiyukf.unicorn.api.ConsultSource;
import com.qiyukf.unicorn.api.ProductDetail;
import com.qiyukf.unicorn.api.Unicorn;
import com.yunlinker.asba.R;
import com.yunlinker.asba.bean.Ad;
import com.yunlinker.asba.bean.URL;
import com.yunlinker.asba.imp.TimeCallback;
import com.yunlinker.asba.networkcallback.PublicMyStringCallBack;
import com.yunlinker.asba.utils.JsonParseUtils;
import com.yunlinker.asba.utils.LogUtills;
import com.yunlinker.asba.utils.MyTimeTask;
import com.yunlinker.asba.utils.Utils;
import com.yunlinker.asba.view.CountDownView;
import com.yunlinker.asba.view.CustomVideoView;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author mars
 */
public class StartActivity extends Activity implements View.OnClickListener, TimeCallback ,View.OnTouchListener {
    private RelativeLayout rootLayout;
    private RelativeLayout adpic_layout;
    private ImageView imageView;
    private CustomVideoView customVideoView;
    private static int sleepTime = 3000;
    private LinearLayout ad_layout;
    private ImageView topad_image;
    private ImageView botomad_image;
    private CountDownView countDownView;
    private boolean isPushedMsg = false;
    private boolean isSkip = false;
    private MyTimeTask myTask;

    @Override
    protected void onCreate(Bundle arg0) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // Translucent status bar
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        setContentView(R.layout.activity_start_cardpass);
        super.onCreate(arg0);
        initUI();
        initData();
        registerEvent();
    }

    private void registerEvent() {
        imageView.setOnClickListener(this);
        countDownView.setOnClickListener(this);
        topad_image.setOnClickListener(this);
        customVideoView.setOnTouchListener(this);
    }

    private void initData() {
        parseIntent();
        myTask = new MyTimeTask(this);
    }

    private void doFunction(ViewGroup layout) {
        AlphaAnimation animation = new AlphaAnimation(0.5f, 1.0f);
        animation.setDuration(500);
        layout.startAnimation(animation);
    }

    private void initUI() {
        rootLayout = (RelativeLayout) findViewById(R.id.splash_root);
        adpic_layout = (RelativeLayout) findViewById(R.id.adpic_layout);
        customVideoView = (CustomVideoView) findViewById(R.id.customVideoView);
        imageView = (ImageView) findViewById(R.id.splash_image);
        ad_layout = (LinearLayout) findViewById(R.id.ad_layout);
        topad_image = (ImageView) findViewById(R.id.topad_image);
        botomad_image = (ImageView) findViewById(R.id.botomad_image);
        countDownView = (CountDownView) findViewById(R.id.countDownView);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!isPushedMsg) {
            getAd(URL.AD_URL);
        }
        /*

         */

    }

    @Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);
        parseIntent();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void parseIntent() {
        Intent intent = getIntent();
        try {
            if (intent.hasExtra(NimIntent.EXTRA_NOTIFY_CONTENT)) {
                if (!Utils.isExsitMianActivity(this, MainActivity.class)) {
                    startActivity(new Intent(StartActivity.this,
                            MainActivity.class).putExtra("sendUrl", ""));
                }
                finish();
                isPushedMsg = true;
//                Log.d("hasExtra",intent.getStringExtra(NimIntent.EXTRA_NOTIFY_CONTENT));
                // 最好将intent清掉，以免从堆栈恢复时又打开客服窗口
                consultService(null);
                setIntent(new Intent());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //

    private void consultService(JSONObject jb) throws JSONException {
        ConsultSource source = new ConsultSource("", "", "");
        if (jb != null && jb.has("goods")) {
            JSONObject goods = jb.getJSONObject("goods");
            ProductDetail.Builder gb = new ProductDetail.Builder();
            gb.setTitle(goods.getString("title"));
            gb.setPicture(goods.getString("picture"));
            gb.setDesc(goods.getString("desc"));
            gb.setNote(goods.getString("note"));
            gb.setAlwaysSend(true);
            source.productDetail = gb.create();
        }
        Unicorn.openServiceActivity(StartActivity.this, "候鸟洋货仓客服", source);
    }


    private void playVideos(String videoUrl) {
        try {
            LogUtills.LogShow("视频", "播放");
            customVideoView.setVideoURI(Uri.parse(videoUrl));
            customVideoView.start();
//            imageView.setVisibility(View.GONE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void playAdpic(String picUrl, ImageView iv, int type) {
        if (picUrl != null && !picUrl.equals("")) {
            if (type == 1) {
                Glide.with(this).load(picUrl).into(iv);
            } else {

                Glide.with(this).load(picUrl).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(iv);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.splash_image:
                sleepTime = 0;
                LogUtills.LogShow("goMain","splash_image点击事件");
                goMain("");
                break;
            case R.id.countDownView:
                try {
                    if (myTask != null)
                        myTask.stopTask();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                sleepTime = 0;
                LogUtills.LogShow("goMain","goMain点击事件");
                goMain("");
                break;
            case R.id.topad_image:
                try {
                    if (myTask != null)
                        myTask.stopTask();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                LogUtills.LogShow("goMain","topad_image点击事件");
                goMain("");
                goMain(ad.getLinkUrl());
                break;

        }
    }


    private void getAd(String url) {
        OkHttpUtils.get().url(url).build().execute(new PublicMyStringCallBack() {
            @Override
            public void onResult(String response) {
                LogUtills.LogShow("请求成功", response);
                parseAdJson(response);
            }

            @Override
            public void onError(String message) {
                imageView.setVisibility(View.VISIBLE);
                LogUtills.LogShow("请求失败", message);
                LogUtills.LogShow("goMain","onError");

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        goMain("");
                    }
                },sleepTime);
            }
        });
    }


    private Ad ad;

    private void parseAdJson(String json) {
        int responseCode = 0;
        try {
            responseCode = (int) JsonParseUtils.getValue(json, "code");
        } catch (Exception e) {
            LogUtills.LogShow("异常", ""+e.getMessage());
            LogUtills.LogShow("goMain","responseCode解析 异常");
            goMain("");
            e.printStackTrace();
        }
        if (responseCode == 1) {
            imageView.setClickable(false);
            try {
                LogUtills.LogShow("解析", "成功");
                Gson gson = new Gson();
                ad = gson.fromJson(JsonParseUtils.getValue(json, "data").toString(), Ad.class);
                LogUtills.LogShow("ad", ad.toString());
                if ("gif".equals(ad.getFaceType())) {
                    playAdpic(ad.getFace(), topad_image, 2);
                } else if ("video".equals(ad.getFaceType())) {
                    playVideos(ad.getFace());
                    topad_image.setVisibility(View.GONE);
                    customVideoView.setVisibility(View.VISIBLE);
                } else {
                    playAdpic(ad.getFace(), topad_image, 1);
                }
                playAdpic(ad.getBottomUrl(), botomad_image, 1);
                countDownView.setTimeDuration(ad.getWaitingTime() * 1000);
                myTask.task(ad.getWaitingTime() * 1000);
                countDownView.start();
                ad_layout.setVisibility(View.VISIBLE);
                doFunction(ad_layout);
            } catch (Exception e) {
                LogUtills.LogShow("异常", ""+e.getMessage());
                LogUtills.LogShow("goMain","code==1 异常");
                goMain("");
                e.printStackTrace();
            }
        } else {
            imageView.setVisibility(View.VISIBLE);
            LogUtills.LogShow("解析", "失败");
            LogUtills.LogShow("goMain","code!=1");
            goMain("");
        }
    }

    @Override
    public void callBack() {
        if (!isSkip) {
            LogUtills.LogShow("广告", "完成");
            LogUtills.LogShow("goMain","callBack");
            goMain("");
        }
    }

    private void goMain(String sendUrl) {
        if("".equals(sendUrl))
         LogUtills.LogShow("goMain", "空值");
        else
            LogUtills.LogShow("goMain", sendUrl);
        startActivity(new Intent(StartActivity.this,
                MainActivity.class).putExtra("sendUrl", sendUrl));
        finish();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        try {
            if (myTask != null)
                myTask.stopTask();
            if (customVideoView != null)
                customVideoView.pause();
            goMain("");
            goMain(ad.getLinkUrl());
            LogUtills.LogShow("goMain","onTouch");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
